import json
import random
from datetime import timedelta

import requests

from raft.static.cluster import CLUSTER_SIZE, Cluster, HEART_BEAT_INTERVAL

cluster = Cluster()


def client_test():
    print("==========客户端测试程序==========")
    print("==========1.读取数据=============")
    print("==========2.写入数据=============")
    print("==========3.退出客户端===========")
    while True:
        print("========请选择你要做的操作=========")
        client_state = int(input())
        if client_state == 1:
            print("======你选择的操作为1.读取数据======")
            read_info = read()
            print(read_info)
        elif client_state == 2:
            print("======你选择的操作为2.写入数据======")
            response = write()
            print(response)
        elif client_state == 3:
            print("======你选择的操作为3.退出客户端=====")
            break


def get_random_url(ids):
    """随机得到一个raft节点"""
    random_raft_id = random.sample(ids, 1)[0]
    ids.remove(random_raft_id)
    raft = cluster[random_raft_id]
    return raft


def read():
    ids = [n for n in range(0, CLUSTER_SIZE)]
    for _ in range(0, len(ids)):
        raft = get_random_url(ids)
        try:
            response = requests.get(f'http://{raft.url}/raft/read')
            if response.status_code == 200:
                return json.loads(response.text)
        except requests.exceptions.ConnectTimeout:
            continue
    return "cluster中所有raft节点皆脱机ing......   "


def write():
    """写入数据"""
    print("==========请输入你要写入的数据==========")
    info = input()
    ids = [n for n in range(0, CLUSTER_SIZE)]
    for _ in range(0, len(ids)):
        raft = get_random_url(ids)
        try:
            response = requests.post(f'http://{raft.url}/raft/write', json={'info': info})
            if response.status_code == 200:
                return json.loads(response.text)
        except requests.exceptions.ConnectTimeout:
            continue
    return "cluster中所有raft节点皆脱机ing......   "


if __name__ == '__main__':
    print("客户端开启")
    client_test()
